#!/bin/sh /etc/rc.common
# Copyright (C) 2008-2012 OpenWrt.org

START=90

start_instance() {
	local cfg="$1"

	config_get type "$cfg" TYPE

	case "$type" in
	  edge)
        config_get_bool enabled "$cfg" 'enabled' '0'
        [ "$enabled" = "0" ] && return 1
        config_get tunname "$cfg" 'tunname'
        config_get mode "$cfg" 'mode'
		config_get ipaddr "$cfg" 'ipaddr'
        config_get netmask "$cfg" 'netmask'
		config_get supernode "$cfg" 'supernode'
		config_get port "$cfg" 'port'
		config_get community "$cfg" 'community'
		config_get key "$cfg" 'key'
		config_get_bool route "$cfg" 'route' '0'
		[ "$route" = "1" ] && args='-r'
        [ "$mode" = 'dhcp' ] && ipaddr='0.0.0.0'
        /usr/sbin/edge -d $tunname -a ${mode}:${ipaddr} -c $community $([ -n "$key" ] && echo -k $key) -s ${netmask} -l ${supernode}:${port} $args
		;;
	  supernode)
        config_get_bool enabled "$cfg" 'enabled' '0'
        [ "$enabled" = "0" ] && return 1
		config_get port "$cfg" port
		/usr/sbin/supernode -l $port &
		;;
	esac
}

stop_instance() {
	local cfg="$1"

	config_get type "$cfg" TYPE

	case "$type" in
	  edge)
		killall -9 edge
		;;
	  supernode)
		killall -9 supernode
		;;
	esac
}

start() {
	config_load 'n2n_v2'
	config_foreach start_instance 'edge'
	config_foreach start_instance 'supernode'
}

stop() {
	config_load 'n2n_v2'
    killall -9 edge
    killall -9 supernode
}
